# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

配置检测模块 - 系统配置和环境检测
包含系统特定配置检测、开发环境检测、bash后门检测等功能
增强的配置验证和错误处理功能
"""

import os
import sys
import json
import time
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()

import subprocess
from core.distro_detection import (
    detect_linux_distro, detect_ubuntu_version, detect_debian_version,
    detect_centos_stream_version, detect_fedora_version, detect_rocky_version,
    detect_almalinux_version, detect_opensuse_version
)
from core.utils import color, color_title, color_green, color_yellow, color_red, color_blue, ml, system_info

# 尝试导入配置验证器
try:
    from config.config_validator import ConfigValidator
    CONFIG_VALIDATOR_AVAILABLE = True
except ImportError:
    CONFIG_VALIDATOR_AVAILABLE = False

# 尝试导入统一日志系统
try:
    from config.unified_logger import get_logger
    logger = get_logger(__name__)
except ImportError:
    import logging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

class EnhancedConfigChecker:
    """增强的配置检查器"""
    
    def __init__(self):
        self.config_cache = {}
        self.validation_results = {}
        self.performance_metrics = {}
        
    def validate_system_config(self, config_path: str = None) -> Dict[str, Any]:
        """验证系统配置"""
        start_time = time.time()
        results = {
            'status': 'success',
            'errors': [],
            'warnings': [],
            'suggestions': [],
            'config_files_checked': [],
            'performance': {}
        }
        
        try:
            # 检查主配置文件
            if config_path:
                config_result = self._check_config_file(config_path)
                results['config_files_checked'].append(config_path)
                results['errors'].extend(config_result.get('errors', []))
                results['warnings'].extend(config_result.get('warnings', []))
                results['suggestions'].extend(config_result.get('suggestions', []))
            
            # 检查系统配置文件
            system_configs = self._get_system_config_files()
            for config_file in system_configs:
                if os.path.exists(config_file):
                    config_result = self._check_system_config_file(config_file)
                    results['config_files_checked'].append(config_file)
                    results['errors'].extend(config_result.get('errors', []))
                    results['warnings'].extend(config_result.get('warnings', []))
            
            # 检查权限和安全设置
            security_result = self._check_security_config()
            results['errors'].extend(security_result.get('errors', []))
            results['warnings'].extend(security_result.get('warnings', []))
            results['suggestions'].extend(security_result.get('suggestions', []))
            
            # 性能指标
            end_time = time.time()
            results['performance'] = {
                'total_time': end_time - start_time,
                'files_checked': len(results['config_files_checked']),
                'errors_found': len(results['errors']),
                'warnings_found': len(results['warnings'])
            }
            
            if results['errors']:
                results['status'] = 'error'
            elif results['warnings']:
                results['status'] = 'warning'
            
            logger.info(f"系统配置验证完成: {results['status']}")
            return results
            
        except Exception as e:
            results['status'] = 'error'
            results['errors'].append(f"配置验证过程中发生错误: {e}")
            logger.error(f"配置验证失败: {e}")
            return results
    
    def _check_config_file(self, config_path: str) -> Dict[str, Any]:
        """检查配置文件"""
        results = {'errors': [], 'warnings': [], 'suggestions': []}
        
        try:
            # 使用配置验证器（如果可用）
            if CONFIG_VALIDATOR_AVAILABLE:
                validator = ConfigValidator()
                is_valid, errors, suggestions = validator.validate_config_file(config_path)
                results['errors'].extend(errors)
                results['suggestions'].extend(suggestions)
                return results
            
            # 基础验证
            if not os.path.exists(config_path):
                results['errors'].append(f"配置文件不存在: {config_path}")
                return results
            
            # 检查文件权限
            if not os.access(config_path, os.R_OK):
                results['errors'].append(f"配置文件无读取权限: {config_path}")
                results['suggestions'].append(f"修改文件权限: chmod 644 {config_path}")
            
            # 检查JSON格式（如果是JSON文件）
            if config_path.endswith('.json'):
                try:
                    with open(config_path, 'r', encoding='utf-8') as f:
                        json.load(f)
                except json.JSONDecodeError as e:
                    results['errors'].append(f"JSON格式错误: {e}")
                    results['suggestions'].append("检查JSON语法，确保所有括号和引号正确匹配")
                except UnicodeDecodeError:
                    results['errors'].append("文件编码错误")
                    results['suggestions'].append("将文件转换为UTF-8编码")
            
            return results
            
        except Exception as e:
            results['errors'].append(f"检查配置文件时发生错误: {e}")
            return results
    
    def _check_system_config_file(self, config_path: str) -> Dict[str, Any]:
        """检查系统配置文件"""
        results = {'errors': [], 'warnings': [], 'suggestions': []}
        
        try:
            # 检查文件存在性和权限
            if not os.path.exists(config_path):
                results['warnings'].append(f"系统配置文件不存在: {config_path}")
                return results
            
            # 检查文件权限
            stat_info = os.stat(config_path)
            file_mode = stat_info.st_mode & 0o777
            
            # 检查敏感配置文件的权限
            if config_path in ['/etc/passwd', '/etc/shadow', '/etc/sudoers']:
                if file_mode & 0o022:  # 检查是否对组和其他用户可写
                    results['errors'].append(f"敏感配置文件权限过于宽松: {config_path} ({oct(file_mode)})")
                    results['suggestions'].append(f"修改文件权限: chmod 644 {config_path}")
            
            # 检查配置文件大小
            file_size = stat_info.st_size
            if file_size > 10 * 1024 * 1024:  # 10MB
                results['warnings'].append(f"配置文件过大: {config_path} ({file_size} bytes)")
                results['suggestions'].append("检查配置文件是否包含不必要的内容")
            
            return results
            
        except Exception as e:
            results['errors'].append(f"检查系统配置文件时发生错误: {e}")
            return results
    
    def _check_security_config(self) -> Dict[str, Any]:
        """检查安全配置"""
        results = {'errors': [], 'warnings': [], 'suggestions': []}
        
        try:
            # 检查SSH配置
            ssh_config = '/etc/ssh/sshd_config'
            if os.path.exists(ssh_config):
                ssh_result = self._check_ssh_config(ssh_config)
                results['errors'].extend(ssh_result.get('errors', []))
                results['warnings'].extend(ssh_result.get('warnings', []))
                results['suggestions'].extend(ssh_result.get('suggestions', []))
            
            # 检查防火墙状态
            firewall_result = self._check_firewall_config()
            results['warnings'].extend(firewall_result.get('warnings', []))
            results['suggestions'].extend(firewall_result.get('suggestions', []))
            
            # 检查日志配置
            log_result = self._check_log_config()
            results['warnings'].extend(log_result.get('warnings', []))
            results['suggestions'].extend(log_result.get('suggestions', []))
            
            return results
            
        except Exception as e:
            results['errors'].append(f"检查安全配置时发生错误: {e}")
            return results
    
    def _check_ssh_config(self, ssh_config_path: str) -> Dict[str, Any]:
        """检查SSH配置"""
        results = {'errors': [], 'warnings': [], 'suggestions': []}
        
        try:
            with open(ssh_config_path, 'r') as f:
                ssh_config_content = f.read()
            
            # 检查root登录设置
            if 'PermitRootLogin yes' in ssh_config_content:
                results['warnings'].append("SSH允许root直接登录")
                results['suggestions'].append("考虑设置 'PermitRootLogin no' 提高安全性")
            
            # 检查密码认证
            if 'PasswordAuthentication yes' in ssh_config_content:
                results['warnings'].append("SSH启用了密码认证")
                results['suggestions'].append("考虑使用密钥认证替代密码认证")
            
            # 检查空密码登录
            if 'PermitEmptyPasswords yes' in ssh_config_content:
                results['errors'].append("SSH允许空密码登录")
                results['suggestions'].append("设置 'PermitEmptyPasswords no'")
            
            return results
            
        except Exception as e:
            results['errors'].append(f"检查SSH配置时发生错误: {e}")
            return results
    
    def _check_firewall_config(self) -> Dict[str, Any]:
        """检查防火墙配置"""
        results = {'warnings': [], 'suggestions': []}
        
        try:
            # 检查iptables状态
            try:
                result = subprocess.run(['iptables', '-L'], capture_output=True, text=True, timeout=5)
                if result.returncode != 0:
                    results['warnings'].append("无法检查iptables状态")
                elif 'Chain INPUT (policy ACCEPT)' in result.stdout:
                    results['warnings'].append("防火墙INPUT链默认策略为ACCEPT")
                    results['suggestions'].append("考虑设置更严格的防火墙规则")
            except (subprocess.TimeoutExpired, FileNotFoundError):
                results['warnings'].append("iptables命令不可用或超时")
            
            # 检查ufw状态
            try:
                result = subprocess.run(['ufw', 'status'], capture_output=True, text=True, timeout=5)
                if result.returncode == 0 and 'Status: inactive' in result.stdout:
                    results['warnings'].append("UFW防火墙未启用")
                    results['suggestions'].append("考虑启用UFW防火墙: sudo ufw enable")
            except (subprocess.TimeoutExpired, FileNotFoundError):
                pass  # ufw可能未安装
            
            return results
            
        except Exception as e:
            results['warnings'].append(f"检查防火墙配置时发生错误: {e}")
            return results
    
    def _check_log_config(self) -> Dict[str, Any]:
        """检查日志配置"""
        results = {'warnings': [], 'suggestions': []}
        
        try:
            # 检查rsyslog配置
            rsyslog_config = '/etc/rsyslog.conf'
            if os.path.exists(rsyslog_config):
                with open(rsyslog_config, 'r') as f:
                    rsyslog_content = f.read()
                
                if '#$ModLoad imudp' in rsyslog_content:
                    results['suggestions'].append("考虑启用rsyslog UDP模块以接收远程日志")
            
            # 检查日志轮转配置
            logrotate_config = '/etc/logrotate.conf'
            if not os.path.exists(logrotate_config):
                results['warnings'].append("logrotate配置文件不存在")
                results['suggestions'].append("安装并配置logrotate以管理日志文件")
            
            # 检查重要日志文件
            important_logs = ['/var/log/auth.log', '/var/log/syslog', '/var/log/secure']
            for log_file in important_logs:
                if os.path.exists(log_file):
                    stat_info = os.stat(log_file)
                    if stat_info.st_size > 100 * 1024 * 1024:  # 100MB
                        results['warnings'].append(f"日志文件过大: {log_file}")
                        results['suggestions'].append(f"考虑轮转日志文件: {log_file}")
            
            return results
            
        except Exception as e:
            results['warnings'].append(f"检查日志配置时发生错误: {e}")
            return results
    
    def _get_system_config_files(self) -> List[str]:
        """获取系统配置文件列表"""
        return [
            '/etc/passwd',
            '/etc/shadow',
            '/etc/group',
            '/etc/sudoers',
            '/etc/ssh/sshd_config',
            '/etc/rsyslog.conf',
            '/etc/logrotate.conf',
            '/etc/crontab',
            '/etc/fstab',
            '/etc/hosts',
            '/etc/resolv.conf'
        ]
    
    def generate_config_report(self, results: Dict[str, Any], output_path: str = None) -> str:
        """生成配置报告"""
        report_lines = []
        report_lines.append("="*80)
        report_lines.append("系统配置验证报告")
        report_lines.append("="*80)
        report_lines.append(f"生成时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        report_lines.append(f"验证状态: {results['status'].upper()}")
        report_lines.append("")
        
        # 性能指标
        if 'performance' in results:
            perf = results['performance']
            report_lines.append("性能指标:")
            report_lines.append(f"  总耗时: {perf.get('total_time', 0):.2f}秒")
            report_lines.append(f"  检查文件数: {perf.get('files_checked', 0)}")
            report_lines.append(f"  发现错误数: {perf.get('errors_found', 0)}")
            report_lines.append(f"  发现警告数: {perf.get('warnings_found', 0)}")
            report_lines.append("")
        
        # 检查的配置文件
        if results.get('config_files_checked'):
            report_lines.append("已检查的配置文件:")
            for config_file in results['config_files_checked']:
                report_lines.append(f"  ✓ {config_file}")
            report_lines.append("")
        
        # 错误
        if results.get('errors'):
            report_lines.append(f"❌ 错误 ({len(results['errors'])}):")
            for i, error in enumerate(results['errors'], 1):
                report_lines.append(f"  {i}. {error}")
            report_lines.append("")
        
        # 警告
        if results.get('warnings'):
            report_lines.append(f"⚠️  警告 ({len(results['warnings'])}):")
            for i, warning in enumerate(results['warnings'], 1):
                report_lines.append(f"  {i}. {warning}")
            report_lines.append("")
        
        # 建议
        if results.get('suggestions'):
            report_lines.append(f"💡 修复建议 ({len(results['suggestions'])}):")
            for i, suggestion in enumerate(results['suggestions'], 1):
                report_lines.append(f"  {i}. {suggestion}")
            report_lines.append("")
        
        if not results.get('errors') and not results.get('warnings'):
            report_lines.append("✅ 所有配置检查通过，无错误或警告")
        
        report_lines.append("="*80)
        
        report_content = "\n".join(report_lines)
        
        # 保存报告
        if output_path:
            try:
                with open(output_path, 'w', encoding='utf-8') as f:
                    f.write(report_content)
                logger.info(f"配置报告已保存到: {output_path}")
            except Exception as e:
                logger.error(f"保存配置报告失败: {e}")
        
        return report_content

# 全局配置检查器实例
enhanced_config_checker = EnhancedConfigChecker()





def check_centos_specific():
    """检测CentOS系统特有配置和路径"""
    try:
        distro = detect_linux_distro()
        if distro != 'centos_based':
            return
            
        color_title("CentOS系统特有配置检测")
        conditions_met = []
        
        # CentOS Stream系统特有条件检测
        if distro == 'centos_stream_based':
            # 检测CentOS Stream特有配置文件
            centos_stream_configs = [
                '/etc/centos-stream-release',
                '/etc/os-release',
                '/etc/yum.repos.d/centos-stream.repo',
                '/etc/yum.repos.d/centos-stream-appstream.repo',
                '/etc/yum.repos.d/centos-stream-baseos.repo',
                '/etc/yum.repos.d/centos-stream-extras.repo',
                '/usr/share/centos-stream-release/',
                '/var/lib/dnf/repos/centos-stream/',
                '/etc/dnf/vars/stream'
            ]
            
            color("检测CentOS Stream特有配置文件:")
            for config in centos_stream_configs:
                if os.path.exists(config):
                    color("✓ CentOS Stream配置: {}".format(config))
                    conditions_met.append("条件满足: CentOS Stream配置{}存在".format(config))
                else:
                    color("○ CentOS Stream配置: {}".format(config))
            
            # 检测CentOS Stream特有服务
            centos_stream_services = [
                'dnf-automatic',
                'dnf-automatic-download',
                'dnf-automatic-install',
                'dnf-automatic-notifyonly',
                'centos-stream-release'
            ]
            
            color("检测CentOS Stream特有服务:")
            for service in centos_stream_services:
                try:
                    result = ml('systemctl list-unit-files | grep {} 2>/dev/null'.format(service))
                    if result.strip():
                        color("✓ CentOS Stream服务: {}".format(service))
                        conditions_met.append("条件满足: CentOS Stream服务{}存在".format(service))
                    else:
                        color("○ CentOS Stream服务: {}".format(service))
                except:
                    color("○ CentOS Stream服务: {} (检测失败)".format(service))
            
            # 获取CentOS Stream版本信息
            centos_stream_info = detect_centos_stream_version()
            
            # 显示CentOS Stream版本信息
            if centos_stream_info['is_centos_stream']:
                color_title("CentOS Stream版本信息")
                color("✓ 检测到CentOS Stream系统")
                if centos_stream_info['version'] != 'unknown':
                    version_text = "版本: CentOS Stream {}".format(centos_stream_info['version'])
                    if centos_stream_info['supported']:
                        if centos_stream_info['support_level'] == 'current':
                            color_green("✓ {} (当前支持版本)".format(version_text))
                        elif centos_stream_info['support_level'] == 'partial':
                            color_yellow("⚠ {} (部分支持)".format(version_text))
                    else:
                        color_red("⚠ {} (不支持版本)".format(version_text))
                        color_red("  警告: 此版本可能不再接受安全更新，建议升级到CentOS Stream 9或更高版本")
                
                if centos_stream_info['architecture'] != 'unknown':
                    color("  架构: {}".format(centos_stream_info['architecture']))
                    if centos_stream_info['is_uefi']:
                        color("  UEFI: 已启用")
                    else:
                        color("  UEFI: 未启用")
                
                conditions_met.append("条件满足: CentOS Stream {}系统".format(centos_stream_info['version']))
        
        # 检测CentOS特有配置文件
        centos_configs = [
            '/etc/yum.conf',
            '/etc/yum.repos.d/',
            '/etc/rpm/macros',
            '/etc/sysconfig/',
            '/etc/redhat-release',
            '/etc/centos-release',
            '/var/log/yum.log',
            '/var/cache/yum/',
            '/usr/share/centos-release/'
        ]
        
        for config in centos_configs:
            if os.path.exists(config):
                color("✓ CentOS配置: {}".format(config))
                conditions_met.append("条件满足: CentOS配置{}存在".format(config))
            else:
                color("○ CentOS配置: {}".format(config))
        
        # 检测CentOS特有服务
        centos_services = [
            'yum-cron',
            'NetworkManager',
            'firewalld',
            'chronyd',
            'rsyslog',
            'systemd-logind'
        ]
        
        for service in centos_services:
            try:
                result = ml('systemctl is-enabled {} 2>/dev/null'.format(service))
                if 'enabled' in result.lower():
                    color("✓ CentOS服务: {} (已启用)".format(service))
                    conditions_met.append("条件满足: CentOS服务{}已启用".format(service))
                else:
                    color("○ CentOS服务: {} (未启用)".format(service))
            except:
                color("○ CentOS服务: {} (检测失败)".format(service))
        
        # 总结CentOS特有条件
        color_title("CentOS系统特有条件总结")
        if conditions_met:
            color("满足 {} 个CentOS特有条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足CentOS特有条件")
            
    except Exception as e:
        color_red("CentOS特有配置检测失败: {}".format(e))


def check_rhel_specific():
    """检测RHEL系列系统特有配置和路径（包括Rocky Linux、AlmaLinux、RHEL等）"""
    try:
        distro = detect_linux_distro()
        if distro != 'rhel_based':
            return
            
        color_title("RHEL系列系统特有配置检测")
        conditions_met = []
        
        # 获取Rocky Linux版本信息
        rocky_info = detect_rocky_version()
        
        # 显示版本信息
        if rocky_info['is_rocky']:
            color_title("Rocky Linux版本信息")
            color("✓ 检测到Rocky Linux系统")
            if rocky_info['version'] != 'unknown':
                version_text = "版本: Rocky Linux {}".format(rocky_info['version'])
                if rocky_info['is_eol']:
                    color_red("⚠ {} (EOL - 生命周期结束)".format(version_text))
                    color_red("  警告: 此版本已不再接受安全更新，建议升级到最新版本")
                else:
                    color("✓ {}".format(version_text))
            
            if rocky_info['architecture'] != 'unknown':
                color("✓ 架构: {}".format(rocky_info['architecture']))
            
            if rocky_info['is_uefi']:
                color("✓ UEFI支持: 是")
                conditions_met.append("条件满足: UEFI启动模式")
            
            # 支持状态
            if rocky_info['support_level'] == 'current':
                color("✓ 支持状态: 当前支持版本")
            elif rocky_info['support_level'] == 'supported':
                color("✓ 支持状态: 长期支持版本")
            elif rocky_info['support_level'] == 'eol':
                color_red("⚠ 支持状态: 生命周期结束")
            else:
                color_yellow("○ 支持状态: 未知")
        
        # 获取AlmaLinux版本信息
        almalinux_info = detect_almalinux_version()
        
        # 显示AlmaLinux版本信息
        if almalinux_info['is_almalinux']:
            color_title("AlmaLinux版本信息")
            color("✓ 检测到AlmaLinux系统")
            if almalinux_info['version'] != 'unknown':
                version_text = "版本: AlmaLinux {}".format(almalinux_info['version'])
                if almalinux_info['is_eol']:
                    color_red("⚠ {} (EOL - 生命周期结束)".format(version_text))
                    color_red("  警告: 此版本已不再接受安全更新，建议升级到最新版本")
                else:
                    color("✓ {}".format(version_text))
            
            if almalinux_info['architecture'] != 'unknown':
                color("✓ 架构: {}".format(almalinux_info['architecture']))
            
            if almalinux_info['is_uefi']:
                color("✓ UEFI支持: 是")
                conditions_met.append("条件满足: UEFI启动模式")
            
            # 支持状态
            if almalinux_info['support_level'] == 'current':
                color("✓ 支持状态: 当前支持版本")
            elif almalinux_info['support_level'] == 'supported':
                color("✓ 支持状态: 长期支持版本")
            elif almalinux_info['support_level'] == 'eol':
                color_red("⚠ 支持状态: 生命周期结束")
            else:
                color_yellow("○ 支持状态: 未知")
        
        # 检测RHEL系列特有配置文件
        rhel_configs = {
            '/etc/redhat-release': 'Red Hat发行版标识文件',
            '/etc/rocky-release': 'Rocky Linux发行版标识文件',
            '/etc/almalinux-release': 'AlmaLinux发行版标识文件',
            '/etc/yum.conf': 'YUM包管理器配置文件',
            '/etc/yum.repos.d/': 'YUM仓库配置目录',
            '/etc/dnf/dnf.conf': 'DNF包管理器配置文件',
            '/etc/rpm/macros': 'RPM宏定义文件',
            '/etc/sysconfig/': '系统配置目录',
            '/var/log/yum.log': 'YUM操作日志',
            '/var/log/dnf.log': 'DNF操作日志',
            '/var/cache/yum/': 'YUM缓存目录',
            '/var/cache/dnf/': 'DNF缓存目录',
            '/usr/share/redhat-release/': 'Red Hat发行版信息目录'
        }
        
        for config_path, description in rhel_configs.items():
            try:
                if os.path.exists(config_path):
                    conditions_met.append("条件满足: {}存在".format(description))
                    color("✓ {}: {}".format(description, config_path))
                    
                    # 检查关键配置文件的权限
                    if config_path in ['/etc/yum.conf', '/etc/dnf/dnf.conf']:
                        if os.access(config_path, os.W_OK):
                            color_yellow("⚠ 警告: {}可写".format(description))
                            conditions_met.append("条件满足: {}可写".format(description))
                else:
                    color("○ {}: {}".format(description, config_path))
            except Exception as e:
                color("○ 检测{}失败: {}".format(description, e))
        
        # 检测SELinux状态
        color_title("SELinux安全模块检测")
        try:
            selinux_status = ml('getenforce 2>/dev/null')
            if selinux_status.strip():
                color("✓ SELinux状态: {}".format(selinux_status.strip()))
                if 'enforcing' in selinux_status.lower():
                    conditions_met.append("条件满足: SELinux处于强制模式")
                elif 'permissive' in selinux_status.lower():
                    conditions_met.append("条件满足: SELinux处于宽松模式")
                elif 'disabled' in selinux_status.lower():
                    color_yellow("⚠ 警告: SELinux已禁用")
                    conditions_met.append("条件满足: SELinux已禁用")
            else:
                color("○ SELinux: 未安装或不可用")
        except:
            color("○ SELinux: 检测失败")
        
        # 总结RHEL系列特有条件
        color_title("RHEL系列系统特有条件总结")
        if rocky_info['is_rocky']:
            color("系统类型: Rocky Linux {}".format(rocky_info['version']))
            color("架构: {}".format(rocky_info['architecture']))
            color("UEFI启动: {}".format('是' if rocky_info['is_uefi'] else '否'))
            color("支持状态: {}".format(rocky_info['support_level']))
        elif almalinux_info['is_almalinux']:
            color("系统类型: AlmaLinux {}".format(almalinux_info['version']))
            color("架构: {}".format(almalinux_info['architecture']))
            color("UEFI启动: {}".format('是' if almalinux_info['is_uefi'] else '否'))
            color("支持状态: {}".format(almalinux_info['support_level']))
        else:
            color("系统类型: RHEL系列 (其他发行版)")
        
        if conditions_met:
            color("满足 {} 个RHEL系列特有条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足RHEL系列特有条件")
            
    except Exception as e:
        color_red("RHEL系列特有配置检测失败: {}".format(e))


def check_path():
    """检测开发工具和环境相关条件"""
    color_title("开发环境条件检测")
    conditions_met = 0
    total_conditions = 12  # 增加包管理工具检测
    
    try:
        # 检测系统类型
        distro = detect_linux_distro()
        
        # 检测各种开发工具和环境的可用性
        tools = {
            "Python2": "python2",
            "Python3": "python3", 
            "Java": "java",
            "Docker": "docker",
            "PHP": "php",
            "Kubernetes": "kubectl",
            "Rust": "rust",
            "C++": "g++",
        }
        
        # 根据系统类型添加包管理工具检测
        if distro == 'debian_based':
            tools.update({
                "APT包管理": "apt",
                "DPKG包管理": "dpkg"
            })
        elif distro == 'rhel_based':
            tools.update({
                "YUM包管理": "yum",
                "RPM包管理": "rpm"
            })
        elif distro == 'fedora_based':
            tools.update({
                "DNF包管理": "dnf",
                "RPM包管理": "rpm",
                "YUM包管理": "yum"  # Fedora也可能有yum作为dnf的别名
            })
        elif distro == 'alpine_based':
            tools.update({
                "APK包管理": "apk"
            })
        
        available_tools = []
        for tool_name, tool_cmd in tools.items():
            try:
                if subprocess.call(["which", tool_cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0:
                    color(tool_name, "可用")
                    available_tools.append(tool_name)
                    conditions_met += 1
                else:
                    color(tool_name, "不可用")
            except subprocess.CalledProcessError:
                color(tool_name, "不可用")
            except Exception:
                color(tool_name, "检测失败")
        
        # 检测PATH环境变量可访问性
        try:
            path_env = os.environ.get('PATH', '')
            if path_env:
                color("PATH环境变量", "可访问")
                conditions_met += 1
                
                # 检测是否包含常见的开发工具路径
                common_paths = ['/usr/bin', '/usr/local/bin', '/bin']
                found_paths = [p for p in common_paths if p in path_env]
                if found_paths:
                    color("常见工具路径", "包含 {} 个".format(len(found_paths)))
                    conditions_met += 1
            else:
                color("PATH环境变量", "无法访问")
        except Exception:
            color("PATH环境变量", "检测失败")
            
    except Exception as e:
        color_red('开发环境检测过程出错', str(e))
    
    # 输出条件检测结果
    color("条件检测结果", "{}/{} 个条件满足".format(conditions_met, total_conditions))
    color("可用工具数量", "{} 个".format(len(available_tools)))
    
    if conditions_met >= 6:
        color("风险评估", "开发环境丰富，便于部署和执行恶意代码")
    elif conditions_met >= 3:
        color("风险评估", "具备基本开发环境，存在一定风险")
    else:
        color("风险评估", "开发环境受限，风险较低")


def check_bash():
    """
    检查bash后门条件 - 支持多Linux发行版
    
    检测系统中bash后门存在的条件，包括：
    1. 检查可疑的bash历史文件操作
    2. 检查异常的bash进程和配置
    3. 检查可疑的shell脚本和后门特征
    4. 支持不同Linux发行版的特定路径和配置
    
    Returns:
        None
        
    Condition Checks:
        - 检查bash历史文件是否被异常清空或修改
        - 检查是否存在可疑的bash进程或脚本
        - 检查bash配置文件是否被篡改
        - 支持Debian/Ubuntu、CentOS/RHEL、Fedora、SUSE、Arch、Alpine、Gentoo等发行版
        
    Output:
        打印bash后门存在的条件信息
    """
    color_title("bash后门条件检测")
    
    try:
        current_user = system_info.get_current_user()
        distro = detect_linux_distro()
        conditions_met = []
        
        # 显示检测环境信息
        distro_names = {
            'debian_based': 'Debian/Ubuntu系列',
            'centos_based': 'CentOS系统',
            'centos_stream_based': 'CentOS Stream系统',
            'rhel_based': 'RHEL系列(Rocky/AlmaLinux/RHEL)',
            'fedora_based': 'Fedora系统',
            'suse_based': 'SUSE系列(openSUSE/SLES)',
            'arch_based': 'Arch Linux系列(Arch/Manjaro)',
            'alpine_based': 'Alpine Linux系统',
            'gentoo_based': 'Gentoo系统',
            'unknown': '未知系统'
        }
        
        # 如果是Debian系列系统，显示详细版本信息
        if distro == 'debian_based':
            ubuntu_info = detect_ubuntu_version()
            debian_info = detect_debian_version()
            
            if ubuntu_info['is_ubuntu']:
                env_info = "Ubuntu {} {}".format(ubuntu_info['version'], ubuntu_info['architecture'])
                if ubuntu_info['is_uefi']:
                    env_info += " UEFI版"
                if ubuntu_info['supported']:
                    env_info += " (已支持)"
                    color_green("[+]检测环境: {}".format(env_info))
                else:
                    env_info += " (版本或架构不完全支持)"
                    color_yellow("[+]检测环境: {}".format(env_info))
            elif debian_info['is_debian']:
                env_info = "Debian {} {}".format(debian_info['version'], debian_info['architecture'])
                if debian_info['is_uefi']:
                    env_info += " UEFI版"
                if debian_info['codename'] != 'Unknown':
                    env_info += " ({})".format(debian_info['codename'])
                
                if debian_info['is_eol']:
                    env_info += " [EOL]"
                    color_red("[+]检测环境: {}".format(env_info))
                    color_red("⚠ 警告: Debian {} 已达到生命周期结束(EOL)".format(debian_info['version']))
                elif debian_info['supported']:
                    env_info += " (已支持)"
                    color_green("[+]检测环境: {}".format(env_info))
                else:
                    env_info += " (版本或架构不完全支持)"
                    color_yellow("[+]检测环境: {}".format(env_info))
            else:
                color_blue("[+]检测环境: {}".format(distro_names.get(distro, '未知系统')))
        else:
            color_blue("[+]检测环境: {}".format(distro_names.get(distro, '未知系统')))
        
        # 根据不同发行版获取特定的历史文件路径
        def get_history_files(user, distro_type):
            """根据发行版和用户获取历史文件路径"""
            base_paths = []
            if system_info.is_root_user():
                base_paths = ['/root']
            else:
                base_paths = ['/home/{}'.format(user)]
                # Alpine和一些发行版可能使用不同的用户目录
                if distro_type == 'alpine_based':
                    base_paths.extend(['/home/{}'.format(user), '/var/home/{}'.format(user)])
            
            history_files = []
            for base_path in base_paths:
                # 标准历史文件
                history_files.extend([
                    '{}/.bash_history'.format(base_path),
                    '{}/.zsh_history'.format(base_path),
                    '{}/.sh_history'.format(base_path)
                ])
                
                # 发行版特定的历史文件
                if distro_type in ['arch_based', 'gentoo_based']:
                    history_files.append('{}/.zsh_history'.format(base_path))
                elif distro_type == 'alpine_based':
                    history_files.extend([
                        '{}/.ash_history'.format(base_path),
                        '{}/.busybox_history'.format(base_path)
                    ])
                elif distro_type in ['debian_based', 'ubuntu_based']:
                    history_files.append('{}/.dash_history'.format(base_path))
                    
                    # Ubuntu和Debian版本特定的历史文件路径优化
                    if distro_type == 'debian_based':
                        ubuntu_info = detect_ubuntu_version()
                        debian_info = detect_debian_version()
                        
                        if ubuntu_info['is_ubuntu']:
                            # Ubuntu 18.04及以上版本支持更多shell
                            if ubuntu_info['version'] in ['24.04', '22.04', '20.04', '18.04']:
                                history_files.extend([
                                    '{}/.fish_history'.format(base_path),
                                    '{}/.local/share/fish/fish_history'.format(base_path)
                                ])
                            
                            # UEFI版本的特殊路径
                            if ubuntu_info['is_uefi']:
                                history_files.extend([
                                    '{}/.efi_history'.format(base_path),
                                    '/boot/efi/.bash_history'
                                ])
                        
                        elif debian_info['is_debian']:
                            # Debian版本特定的历史文件路径优化
                            version_num = float(debian_info['version']) if debian_info['version'] != 'Unknown' else 0
                            
                            # Debian 12.x (Bookworm) 及以上版本支持更多shell
                            if version_num >= 12.0:
                                history_files.extend([
                                    '{}/.fish_history'.format(base_path),
                                    '{}/.local/share/fish/fish_history'.format(base_path),
                                    '{}/.zsh_history'.format(base_path)
                                ])
                            
                            # UEFI版本的特殊路径
                            if debian_info['is_uefi']:
                                history_files.extend([
                                    '{}/.efi_history'.format(base_path),
                                    '/boot/efi/.bash_history'
                                ])
                                
            return history_files
        
        # 条件1: 检查可疑的bash历史文件操作
        color_title("bash历史文件检测")
        history_files = get_history_files(current_user, distro)
        
        suspicious_history = False
        for history_file in history_files:
            if os.path.exists(history_file):
                try:
                    # 使用safe_file_read方法来确保Python 2/3兼容性
                    content = system_info.safe_file_read(history_file)
                    if content is not None:
                        if content.strip():
                            # 检查历史文件中的可疑命令
                            suspicious_commands = ['nc -l', 'python -c', 'bash -i', '/dev/tcp/', 'mkfifo', 'nohup', 'disown']
                            for cmd in suspicious_commands:
                                if cmd in content:
                                    color_yellow("⚠ 历史文件中发现可疑命令: {} - {}".format(history_file, cmd))
                                    suspicious_history = True
                            color("○ 历史文件正常: {}".format(history_file))
                        else:
                            # 空的历史文件可能表示被清空
                            file_stat = os.stat(history_file)
                            if file_stat.st_mtime > file_stat.st_ctime:  # 修改时间晚于创建时间
                                color_yellow("⚠ 历史文件可能被清空: {}".format(history_file))
                                suspicious_history = True
                            else:
                                color("○ 历史文件为空但正常: {}".format(history_file))
                except Exception as e:
                    color_red("无法读取历史文件: {} - {}".format(history_file, e))
            else:
                color("○ 历史文件不存在: {}".format(history_file))
        
        if suspicious_history:
            conditions_met.append("条件满足: 发现可疑的bash历史文件操作")
        
        # 条件2: 检查可疑的bash进程
        try:
            # 获取详细的bash进程信息
            bash_processes_detail = ml('ps aux | grep -E "(bash|sh)" | grep -v grep').strip()
            if bash_processes_detail:
                bash_lines = bash_processes_detail.split('\n')
                bash_count = len(bash_lines)
                color("○ 系统中运行 {} 个bash/sh进程".format(bash_count))
                
                # 检查可疑的bash进程
                suspicious_processes = []
                for line in bash_lines:
                    # 检查是否有可疑的bash命令行参数
                    if any(pattern in line for pattern in ['-i', '/dev/tcp/', 'nc -l', 'python -c', 'mkfifo']):
                        suspicious_processes.append(line.strip())
                    # 检查是否有异常的网络连接bash进程
                    if 'bash -i' in line or '/dev/tcp/' in line:
                        suspicious_processes.append(line.strip())
                
                if suspicious_processes:
                    conditions_met.append("条件满足: 发现可疑的bash进程")
                    color_red("⚠ 发现可疑的bash进程:")
                    for proc in suspicious_processes:
                        color_red("  {}".format(proc))
                else:
                    color("○ bash进程运行正常")
            else:
                color("○ 系统中无bash/sh进程运行")
        except Exception as e:
            color_red("检查bash进程失败: {}".format(e))
        
        # 条件3: 检查可疑的网络工具组合
        def get_network_tools(distro_type):
            """根据发行版获取网络工具列表"""
            normal_tools = ['wget', 'curl']
            suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat']
            
            if distro_type == 'alpine_based':
                # Alpine可能使用不同的工具名称
                normal_tools.extend(['busybox wget', 'busybox nc'])
                suspicious_tools.extend(['busybox telnet'])
            elif distro_type in ['arch_based', 'gentoo_based']:
                # Arch和Gentoo可能有额外的网络工具
                suspicious_tools.extend(['nmap', 'netcat-openbsd'])
            elif distro_type == 'debian_based':
                # Debian系列特定工具
                suspicious_tools.extend(['netcat-traditional', 'netcat-openbsd'])
            elif distro_type in ['fedora_based', 'rhel_based', 'centos_based', 'centos_stream_based']:
                # Red Hat系列工具
                suspicious_tools.extend(['nmap-ncat'])
            elif distro_type == 'suse_based':
                # SUSE系列工具
                suspicious_tools.extend(['netcat-openbsd'])
            
            return normal_tools, suspicious_tools
        
        normal_tools, suspicious_tools = get_network_tools(distro)
        
        available_normal = []
        available_suspicious = []
        
        for tool in normal_tools:
            try:
                result = ml('which {}'.format(tool))
                if result.strip():
                    available_normal.append(tool)
            except Exception:
                pass
                
        for tool in suspicious_tools:
            try:
                result = ml('which {}'.format(tool))
                if result.strip():
                    available_suspicious.append(tool)
            except Exception:
                pass
        
        if available_normal:
            color("○ 可用下载工具: {}".format(', '.join(available_normal)))
        
        if available_suspicious:
            # 检查是否有多个可疑工具或与正常工具组合
            if len(available_suspicious) >= 2 or (available_suspicious and available_normal):
                conditions_met.append("条件满足: 存在可疑的网络工具组合")
                color_yellow("⚠ 发现可疑网络工具: {}".format(', '.join(available_suspicious)))
            else:
                color("○ 发现网络工具: {}".format(', '.join(available_suspicious)))
        
        if not available_normal and not available_suspicious:
            color("○ 系统中无可用网络工具")
        
        # 条件4: 检查可疑的环境变量配置
        try:
            def get_suspicious_env_vars(distro_type):
                """根据发行版获取可疑环境变量列表"""
                base_vars = ['LD_PRELOAD', 'LD_LIBRARY_PATH', 'PROMPT_COMMAND']
                
                if distro_type == 'alpine_based':
                    # Alpine特定环境变量
                    base_vars.extend(['MUSL_LOCPATH', 'BUSYBOX_ASH_CMDLINE_HIST'])
                elif distro_type in ['arch_based', 'gentoo_based']:
                    # Arch和Gentoo特定环境变量
                    base_vars.extend(['ZDOTDIR', 'ZSH_CUSTOM'])
                elif distro_type == 'debian_based':
                    # Debian系列特定环境变量
                    base_vars.extend(['DEBIAN_FRONTEND'])
                elif distro_type in ['fedora_based', 'rhel_based', 'centos_based', 'centos_stream_based']:
                    # Red Hat系列特定环境变量
                    base_vars.extend(['SYSTEMD_PAGER', 'RHEL_ALLOW_PYTHON2_FOR_BUILD'])
                elif distro_type == 'suse_based':
                    # SUSE系列特定环境变量
                    base_vars.extend(['SUSE_ASNEEDED'])
                
                return base_vars
            
            # 检查是否有可疑的环境变量
            suspicious_env_vars = get_suspicious_env_vars(distro)
            suspicious_found = []
            
            for env_var in suspicious_env_vars:
                try:
                    env_value = ml('echo ${}'.format(env_var))
                    # 只有当环境变量有实际值且不是变量名本身时才认为可疑
                    if env_value.strip() and env_value.strip() != '${}'.format(env_var):
                        suspicious_found.append("{}={}".format(env_var, env_value.strip()))
                except Exception:
                    pass
            
            shell_env = ml('echo $SHELL')
            if shell_env.strip():
                color("○ 当前shell环境: {}".format(shell_env.strip()))
            
            if suspicious_found:
                conditions_met.append("条件满足: 发现可疑的环境变量配置")
                color_yellow("⚠ 发现可疑环境变量:")
                for env in suspicious_found:
                    color_yellow("  {}".format(env))
            else:
                color("○ 未发现可疑环境变量配置")
        except Exception:
            color("○ 环境变量检测失败")
        
        # 总结条件检测结果
        color_title("bash后门条件总结")
        if conditions_met:
            color("满足 {} 个bash后门条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未满足bash后门的基本条件")
            
    except Exception as e:
        color_red("bash条件检测失败: {}".format(e))


def check_network_tools():
    """
    检查可疑网络工具 - 支持多Linux发行版
    
    检测系统中可疑网络工具的存在，包括：
    1. 检查正常和可疑的网络工具
    2. 根据不同Linux发行版检测特定工具
    3. 检查UEFI相关的网络工具（部分发行版）
    4. 支持Debian/Ubuntu、CentOS/RHEL、Fedora、SUSE、Arch、Alpine、Gentoo等发行版
    
    Returns:
        None
        
    Condition Checks:
        - 检查系统中是否存在可疑的网络工具
        - 检查工具的可执行权限和位置
        - 根据发行版特性检测特定的网络工具
        - 检查UEFI环境下的特殊网络工具
        
    Output:
        打印网络工具检测结果和风险评估
    """
    color_title("可疑网络工具检测")
    
    try:
        distro = detect_linux_distro()
        conditions_met = []
        
        # 显示检测环境信息
        distro_names = {
            'debian_based': 'Debian/Ubuntu系列',
            'centos_based': 'CentOS系统',
            'centos_stream_based': 'CentOS Stream系统',
            'rhel_based': 'RHEL系列(Rocky/AlmaLinux/RHEL)',
            'fedora_based': 'Fedora系统',
            'suse_based': 'SUSE系列(openSUSE/SLES)',
            'arch_based': 'Arch Linux系列(Arch/Manjaro)',
            'alpine_based': 'Alpine Linux系统',
            'gentoo_based': 'Gentoo系统',
            'unknown': '未知系统'
        }
        
        # 如果是Debian系列系统，显示详细版本信息
        if distro == 'debian_based':
            ubuntu_info = detect_ubuntu_version()
            debian_info = detect_debian_version()
            
            if ubuntu_info['is_ubuntu']:
                env_info = "Ubuntu {} {}".format(ubuntu_info['version'], ubuntu_info['architecture'])
                if ubuntu_info['is_uefi']:
                    env_info += " UEFI版"
                if ubuntu_info['supported']:
                    env_info += " (已支持)"
                    color_green("[+]检测环境: {}".format(env_info))
                else:
                    env_info += " (版本或架构不完全支持)"
                    color_yellow("[+]检测环境: {}".format(env_info))
            elif debian_info['is_debian']:
                env_info = "Debian {} {}".format(debian_info['version'], debian_info['architecture'])
                if debian_info['is_uefi']:
                    env_info += " UEFI版"
                if debian_info['codename'] != 'Unknown':
                    env_info += " ({})".format(debian_info['codename'])
                
                if debian_info['is_eol']:
                    env_info += " [EOL]"
                    color_red("[+]检测环境: {}".format(env_info))
                    color_red("⚠ 警告: Debian {} 已达到生命周期结束(EOL)".format(debian_info['version']))
                elif debian_info['supported']:
                    env_info += " (已支持)"
                    color_green("[+]检测环境: {}".format(env_info))
                else:
                    env_info += " (版本或架构不完全支持)"
                    color_yellow("[+]检测环境: {}".format(env_info))
            else:
                color_blue("[+]检测环境: {}".format(distro_names.get(distro, '未知系统')))
        else:
            color_blue("[+]检测环境: {}".format(distro_names.get(distro, '未知系统')))
        
        # 根据不同发行版定义正常和可疑的网络工具
        def get_network_tools_by_distro(distro_type):
            """根据发行版获取网络工具列表"""
            normal_tools = []
            suspicious_tools = []
            
            if distro_type == 'alpine_based':
                normal_tools = ['wget', 'curl', 'ping', 'traceroute']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark']
                # Alpine特有的BusyBox工具
                normal_tools.extend(['busybox wget', 'busybox ping'])
                suspicious_tools.extend(['busybox nc', 'busybox telnet', 'busybox traceroute'])
                
            elif distro_type in ['arch_based']:
                normal_tools = ['wget', 'curl', 'ping', 'traceroute', 'dig', 'nslookup']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark', 'masscan', 'zmap']
                # Arch特有工具
                suspicious_tools.extend(['netcat-openbsd', 'gnu-netcat'])
                
            elif distro_type in ['gentoo_based']:
                normal_tools = ['wget', 'curl', 'ping', 'traceroute', 'dig', 'nslookup']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark']
                # Gentoo特有工具
                suspicious_tools.extend(['netcat6'])
                
            elif distro_type == 'debian_based':
                normal_tools = ['wget', 'curl', 'ping', 'ping6', 'traceroute', 'traceroute6', 'dig', 'nslookup', 'host']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark', 'masscan', 'zmap']
                # Debian/Ubuntu特有工具
                suspicious_tools.extend(['netcat-traditional', 'netcat-openbsd', 'nc.traditional', 'nc.openbsd'])
                
                # 检查是否为Ubuntu或Debian的UEFI版本，添加UEFI相关网络工具
                ubuntu_info = detect_ubuntu_version()
                debian_info = detect_debian_version()
                
                if ubuntu_info['is_ubuntu'] and ubuntu_info['is_uefi']:
                    # Ubuntu UEFI版本可能有额外的网络工具
                    suspicious_tools.extend(['efibootmgr', 'mokutil'])
                elif debian_info['is_debian'] and debian_info['is_uefi']:
                    # Debian UEFI版本可能有额外的网络工具
                    suspicious_tools.extend(['efibootmgr', 'mokutil'])
                
            elif distro_type in ['fedora_based']:
                normal_tools = ['wget', 'curl', 'ping', 'ping6', 'traceroute', 'traceroute6', 'dig', 'nslookup', 'host']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark', 'masscan', 'zmap']
                # Fedora特有工具
                suspicious_tools.extend(['nmap-ncat'])
                
            elif distro_type in ['rhel_based', 'centos_based', 'centos_stream_based']:
                normal_tools = ['wget', 'curl', 'ping', 'ping6', 'traceroute', 'traceroute6', 'dig', 'nslookup', 'host']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark']
                # RHEL/CentOS特有工具
                suspicious_tools.extend(['nmap-ncat'])
                
            elif distro_type == 'suse_based':
                normal_tools = ['wget', 'curl', 'ping', 'ping6', 'traceroute', 'traceroute6', 'dig', 'nslookup', 'host']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark']
                # SUSE特有工具
                suspicious_tools.extend(['netcat-openbsd'])
                
                # 检查是否为openSUSE的UEFI版本
                opensuse_info = detect_opensuse_version()
                if opensuse_info['is_opensuse'] and opensuse_info['is_uefi']:
                    suspicious_tools.extend(['efibootmgr', 'mokutil'])
                
            else:
                # 默认工具列表
                normal_tools = ['wget', 'curl', 'ping', 'traceroute', 'dig', 'nslookup']
                suspicious_tools = ['nc', 'netcat', 'telnet', 'socat', 'ncat', 'nmap', 'tcpdump', 'wireshark', 'tshark']
            
            return normal_tools, suspicious_tools
        
        normal_tools, suspicious_tools = get_network_tools_by_distro(distro)
        
        # 检测正常网络工具
        color_title("正常网络工具检测")
        available_normal = []
        for tool in normal_tools:
            try:
                result = ml('which {} 2>/dev/null'.format(tool))
                if result.strip():
                    available_normal.append(tool)
                    color("✓ 正常工具: {} - {}".format(tool, result.strip()))
                else:
                    color("○ 正常工具: {} (未安装)".format(tool))
            except Exception:
                color("○ 正常工具: {} (检测失败)".format(tool))
        
        # 检测可疑网络工具
        color_title("可疑网络工具检测")
        available_suspicious = []
        for tool in suspicious_tools:
            try:
                result = ml('which {} 2>/dev/null'.format(tool))
                if result.strip():
                    available_suspicious.append(tool)
                    color_yellow("⚠ 可疑工具: {} - {}".format(tool, result.strip()))
                    
                    # 检查工具的权限
                    try:
                        tool_path = result.strip()
                        if os.access(tool_path, os.X_OK):
                            color_yellow("  权限: 可执行")
                            conditions_met.append("条件满足: 可疑网络工具{}可执行".format(tool))
                        else:
                            color("  权限: 不可执行")
                    except Exception:
                        color("  权限: 检测失败")
                else:
                    color("○ 可疑工具: {} (未安装)".format(tool))
            except Exception:
                color("○ 可疑工具: {} (检测失败)".format(tool))
        
        # 检查工具组合风险
        color_title("网络工具风险评估")
        
        # 统计工具数量
        normal_count = len(available_normal)
        suspicious_count = len(available_suspicious)
        total_count = normal_count + suspicious_count
        
        color("正常网络工具数量: {}".format(normal_count))
        color("可疑网络工具数量: {}".format(suspicious_count))
        color("总网络工具数量: {}".format(total_count))
        
        # 风险评估
        if suspicious_count >= 5:
            color_red("⚠ 高风险: 系统中存在大量可疑网络工具")
            conditions_met.append("条件满足: 存在大量可疑网络工具({}个)".format(suspicious_count))
        elif suspicious_count >= 3:
            color_yellow("⚠ 中风险: 系统中存在多个可疑网络工具")
            conditions_met.append("条件满足: 存在多个可疑网络工具({}个)".format(suspicious_count))
        elif suspicious_count >= 1:
            color_yellow("⚠ 低风险: 系统中存在少量可疑网络工具")
            conditions_met.append("条件满足: 存在可疑网络工具({}个)".format(suspicious_count))
        else:
            color_green("✓ 无风险: 系统中未发现可疑网络工具")
        
        # 检查特定的危险工具组合
        dangerous_combinations = [
            ['nc', 'nmap'],
            ['netcat', 'tcpdump'],
            ['socat', 'wireshark'],
            ['ncat', 'tshark']
        ]
        
        for combo in dangerous_combinations:
            if all(tool in available_suspicious for tool in combo):
                color_red("⚠ 危险组合: 发现 {} 工具组合".format(' + '.join(combo)))
                conditions_met.append("条件满足: 存在危险工具组合({})".format(' + '.join(combo)))
        
        # 总结网络工具检测结果
        color_title("网络工具检测总结")
        if conditions_met:
            color("满足 {} 个可疑网络工具条件:".format(len(conditions_met)))
            for condition in conditions_met:
                color("  • {}".format(condition))
        else:
            color("未发现可疑网络工具条件")
        
        # 显示可用工具列表
        if available_normal:
            color("可用正常工具: {}".format(', '.join(available_normal)))
        if available_suspicious:
            color_yellow("可用可疑工具: {}".format(', '.join(available_suspicious)))
            
    except Exception as e:
        color_red("网络工具检测失败: {}".format(e))